package org.paradise.dms.web.tools;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;

public class AnnotationSessionFactoryBeanExt extends AnnotationSessionFactoryBean {

	private Logger log = Logger.getLogger(getClass());

	protected String resolveBasePackage(String basePackage) {
		return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
	}

	@SuppressWarnings("unchecked")
	public void setAnnotatedClasses(Class[] annotatedClasses) {
		try {
			// 这里读取所有的VO
			PathMatchingResourcePatternResolver pnrpr = new PathMatchingResourcePatternResolver();
			String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage("org.paradise") + "/" + "**/*.class";
			Resource[] resources = pnrpr.getResources(packageSearchPath);
			MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(pnrpr);
			for (int i = 0; i < resources.length; i++) {
				Resource resource = resources[i];
				MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
				AnnotationMetadata c = metadataReader.getAnnotationMetadata();

				try {
					Class testCls = Class.forName(c.getClassName());
					if (testCls.isAnnotationPresent(javax.persistence.Entity.class)) {
						// 发现目标
						// javax.persistence.Entity an = (Entity)
						// testCls.getAnnotation(javax.persistence.Entity.class);
						ServerConfig.serverVoList.add(testCls);
					}
				} catch (ClassNotFoundException e) {
				}
			}
		} catch (IOException e) {
			log.warn("", e);
		}

		Class[] annotatedClassesPrepare = new Class[annotatedClasses.length + ServerConfig.serverVoList.size()];
		System.arraycopy(annotatedClasses, 0, annotatedClassesPrepare, 0, annotatedClasses.length);

		for (int i = 0; i < ServerConfig.serverVoList.size(); i++) {
			log.info("VO: " + ServerConfig.serverVoList.get(i).getName());
			annotatedClassesPrepare[annotatedClasses.length + i] = ServerConfig.serverVoList.get(i);
		}

		super.setAnnotatedClasses(annotatedClassesPrepare);
	}

}
